﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TA.JSON;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Definition of a property which JSON-serializes its value.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class JsonPropertyDefinition<T> : PropertyDefinition<T>
		where T : class, IJsonCompatible, new()
	{
		/// <summary>
		/// Ctor.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="shortName"></param>
		/// <param name="defaultValue"></param>
		public JsonPropertyDefinition(string name, string shortName, T defaultValue)
			: base(name, shortName, defaultValue)
		{
		}
		/// <summary>
		/// Returns true if the value of this property for the specified control is equal to the default, otherwise false.
		/// </summary>
		/// <param name="control"></param>
		/// <returns></returns>
		protected override bool ValueIsDefault(TControl control)
		{
			return !this.GetValue(control).IsDirty;
		}
		/// <summary>
		/// Gets the default value for this property for the specified control.
		/// </summary>
		/// <param name="control"></param>
		/// <returns></returns>
		protected override T GetDefaultValue(TControl control)
		{
			T t = new T();
			if (t is IControlOwned)
				((IControlOwned)t).SetOwner(control);
			control._State[this.Name] = t;
			return t;
		}
		/// <summary>
		/// Serializes the value of this property for the specified control to the specified <see cref="JsonWriter"/>.
		/// </summary>
		/// <param name="control"></param>
		/// <param name="jw"></param>
		protected override void DoSerializeValue(TControl control, JsonWriter jw)
		{
			T t = this.GetValue(control);
			if (t == null)
			{
				jw.Null();
			}
			else
			{
				t.Serialize(jw);
			}
		}
		/// <summary>
		/// Deserializes the value of this property from the specified <see cref="JsonReader"/>.
		/// </summary>
		/// <param name="control"></param>
		/// <param name="jr"></param>
		public override void DeserializeValue(TControl control, JsonReader jr)
		{
			if (jr.TokenType == JsonToken.Null)
			{
				this.SetValue(control, null);
			}
			else
			{
				T t = new T();
				t.Deserialize(jr);
				this.SetValue(control, t);
			}
		}
	}
}
